package com.bootdo.imgtext.check.impl;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.bootdo.imgtext.check.CheckService;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class KepuImpl extends CheckService {

	public KepuImpl(String url) {

		try (final WebClient webClient = new WebClient(BrowserVersion.CHROME);) {
			webClient.getOptions().setThrowExceptionOnScriptError(false);// 当JS执行出错的时候是否抛出异常, 这里选择不需要
			webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);// 当HTTP的状态非200时是否抛出异常, 这里选择不需要
			webClient.getOptions().setActiveXNative(false);
			webClient.getOptions().setCssEnabled(false);// 是否启用CSS, 因为不需要展现页面, 所以不需要启用
			webClient.getOptions().setJavaScriptEnabled(true); // 很重要，启用JS
			webClient.setAjaxController(new NicelyResynchronizingAjaxController());// 很重要，设置支持AJAX

			HtmlPage page = webClient.getPage(url);
			webClient.waitForBackgroundJavaScript(30000);
			
			Document document = Jsoup.parse(page.asXml());
			document.setBaseUri(url);
			
			Elements head = document.select("div.left").select("div");
			if (head.size()>3) {
				author = head.get(2).text().trim();
			}
			
			Elements content = document.select("div.font_size14").select(".line_height25").select("p");
			Elements imgs = content.select("img[src]");
			checkImgs(imgs);
		} catch (Exception e) {
			exception = e.toString();
		}

	}
}
